<template>
	<view style="background-color: #F2F2F2 ;width: 100vw;height: 100vh;overflow-y: scroll;">
		<view style="background-color: #ffffff;padding-bottom: 8px;margin-bottom: 10px;">
			<u-tabs :list="list1" @click="click" scrollable='false' :current='roof' lineColor='#FFDA00'
				itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;width:25vw"
				:activeStyle="{ color: '#303133',fontWeight: 'bold',transform: 'scale(1.05)'}"></u-tabs>
		</view>
		<view v-for="(item,index) in substance[0]" :key="index" style="margin-bottom: 9px;">
			<view class="cycle">
				<view class="cycleUp" style="margin-top: 0;margin-bottom: 5px;">
					<view style="width: calc(75vw - 60px);">
						{{item.type == '0' ?'整租' : '合租'}}·{{item.villageName}}{{item.address}}{{item.houseNo}}
					</view>
					<view style="color:#FF0000 ;display: flex;align-items: center;" class="upRight">
						¥{{item.price}}/{{item.payType}}
					</view>
				</view>
				<view style="font-size: 12px;">
					{{item.type == '0' ? item.houseArea : item.roomArea}}㎡
				</view>
				<view class="cycleUp">
					<view class="upUp">
						看房时间
					</view>
					<view class="upRight" v-if="item.viewHouseTime">
						<!-- 2024-1212 08:00 -->
						{{item.viewHouseTime}}:00
					</view>
				</view>
				<view class="cycleUp">
					<view class="upUp">
						看房地址
					</view>
					<view class="upRight">
						{{item.villageName}}{{item.address}}
					</view>
				</view>
				<view class="cycleUp" v-if="item.isPhysicalKey=='电子密码'">
					<view class="upUp" style="width: 115px;">
						钥匙状态
					</view>
					<view class="upRight" style="width: calc(100vw - 170px);text-align: right;">
						动态密码
					</view>
				</view>
				<view class="cycleUp" v-if="item.isPhysicalKey=='电子密码'">
					<view class="upUp" style="width: 115px;">
						看房时长
					</view>
					<view class="upRight" style="width: calc(100vw - 170px);text-align: right;">
						1小时
					</view>
				</view>
				<view class="cycleUp" v-if="item.isPhysicalKey=='实体钥匙'">
					<view class="upUp">
						钥匙托管门店电话
					</view>
					<view class="upRight">
						{{item.phoneNumber}}
					</view>
					<view style="margin-left: 3px;" @click="telephone(item.phoneNumber)">
						<u-icon name="phone-fill"></u-icon>
					</view>
				</view>
				<view class="cycleUp" v-if="item.isPhysicalKey=='实体钥匙'">
					<view class="upUp" style="width: 115px;">
						钥匙管理人地址
					</view>
					<view class="upRight" style="width: calc(100vw - 170px);text-align: right;">
						{{item.keyAddress}}
					</view>
				</view>
				<view v-if="headnavigation==0" class="pushButton">
					<button v-if="item.isPhysicalKey=='实体钥匙'"
						@click="yaoshi(item.houseId,item.id,item.keyAddress,item.isPhysicalKey)">去拿钥匙</button>
					<button v-if="item.isPhysicalKey=='电子密码'"
						@click="mima(item.keyType,item.houseId,item.id)">查看密码</button>
				</view>
				<view v-if="headnavigation==1">
					<!-- 已拿钥匙 -->
				</view>
				<view v-if="headnavigation==2" class="pushButton">
					<!-- 已看房 -->
					<button v-show="item.keyView == '0'" @click="comment(item.houseId)">去评论</button>
					<button v-show="item.keyView == '0'" @click="qiatan(item.ownerPhone)">与房东直联</button>
					<button v-show="item.keyView == '0'"
						@click="signup(item.houseId,item.price,item.payType)">远程签约</button>
					<button v-show="item.keyView == 1" @click="payment">待支付</button>
					<button v-show="item.keyView == 1" @click="contractView(item.signFlowId)">查看合同</button>
				</view>
				<view v-if="headnavigation==3" class="pushButton">
					<!-- 已签付 -->
					<!-- <button>去评论</button> -->
					<button v-if="item.state==3">已支付</button>
					<button v-else-if="item.keyView != 2" @click="gopay(item.houseId)">未支付</button>
					<button v-show="item.keyView != 2" @click="contractView(item.signFlowId)">查看合同</button>
					<view style="color: red;font-family: fangsong;font-weight: bold;" v-show="item.keyView == 2">房东已拒绝签约
					</view>
				</view>
				<u-empty v-if="substance.length==0" mode="data" icon="/static/index/homeowner/history.png">
				</u-empty>
			</view>
		</view>
		<u-modal :show="show" :title="title" showCancelButton="true" @cancel="cancelss" @confirm="start">
			<view class="slot-content">
				<!-- <input type="text" /> -->
				<view style="display: flex;justify-content: space-between;align-items: center;margin: 10px 0;">
					<view style="margin-right: 5px;font-size: 14px;width: 30px;">
						最终价格
					</view>
					<view class="">
						<u-input placeholder="请输入您的最终成交价" border="surround" v-model="selecteds.price"
							inputAlign='right'></u-input>
					</view>
					<view style="width: 26px;">
						/元
					</view>
				</view>
				<view style="display: flex;justify-content: space-between;align-items: center;margin: 10px 0;">
					<view style="margin-right: 5px;font-size: 14px;width: 60px;">
						支付周期
					</view>
					<view @click="paymentss">
						<u-input placeholder="支付方式(推荐月付)" border="surround" v-model="selecteds.specific" disabled='true'
							disabledColor='#ffffff' inputAlign='right'></u-input>
					</view>
				</view>
				<view style="display: flex;justify-content: space-between;align-items: center;margin: 10px 0;">
					<view style="margin-right: 5px;font-size: 14px;width: 30px;">
						入住时间
					</view>
					<view class="">
						<u-input placeholder="交房租时间(推荐15号)" border="surround" v-model="selecteds.approximately"
							inputAlign='right'></u-input>
					</view>
					<view style="width: 26px;">
						/号
					</view>
				</view>
				<view style="display: flex;justify-content: space-between;align-items: center;margin: 10px 0;">
					<view style="margin-right: 5px;font-size: 14px;width: 30px;">
						租期
					</view>
					<view class="">
						<u-input placeholder="租期" border="surround" v-model="selecteds.rentDate"
							inputAlign='right'></u-input>
					</view>
					<view style="width: 26px;">
						月
					</view>
				</view>
				<view style="display: flex;justify-content: space-between;align-items: center;margin: 10px 0;">
					<view style="margin-right: 5px;font-size: 14px;width: 30px;">
						押金
					</view>
					<view class="">
						<u-input placeholder="押金" border="surround" v-model="selecteds.deposit"
							inputAlign='right'></u-input>
					</view>
					<view style="width: 26px;">
						/元
					</view>
				</view>
			</view>
		</u-modal>
	</view>
</template>
<script setup>
	import {
		reactive,
		ref
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		get,
		post,
	} from '@/serve/method.js'
	import {
		test
	} from '@/uni_modules/uview-plus';
	onLoad((option) => {
		roof.value = option.id
		click(option.id)
		uni.getStorage({
			key: 'lifeData',
			success: function(res) {
				userId.value = res.data.vuex_user.userId
			},
			fail: function(res) {
				if (res.errMsg == 'getStorage:fail data not found') {
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}
			}
		})
	})
	const telephone = (item) => {
		uni.makePhoneCall({
			phoneNumber: item,
		});
	}
	// 支付周期
	const paymentss = () => {
		uni.showActionSheet({
			itemList: ['周付', '月付', '季付', '年付'],
			success: function(res) {
				console.log(res)
				console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
				if (res.tapIndex == 0) {
					selecteds.specific = '周付'
				}
				if (res.tapIndex == 1) {
					selecteds.specific = '月付'
				}
				if (res.tapIndex == 2) {
					selecteds.specific = '季付'
				}
				if (res.tapIndex == 3) {
					selecteds.specific = '年付'
				}
			},
			fail: function(res) {
				console.log(res.errMsg);
			}
		});
	}
	const qiatan = (item) => {
		uni.showModal({
			title: '提示',
			content: '邻里帮租便民互助平台不收取任何中介佣金及其他服务费用， 平台将为您与已核实的房屋权益房东提供免费公正租约和后续入住服务， 包括： 平价保洁、 家电维修、 保险、 房屋修复、 转租等服务； 若线下成交， 平台将无法为您提供保障权益服务；',
			success: function(res) {
				if (res.confirm) {
					uni.showModal({
						title: '提示',
						content: '房东电话号码是：' + item,
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.makePhoneCall({
									phoneNumber: item,
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	const contractView = (item) => {
		console.log(7777)
		let url = `/api/user/viewContract/${item}`
		get(url).then((res) => {
			console.log(res.data, 88888)
			let fileUrl = res.data
			uni.downloadFile({
				url: fileUrl,
				success: function(res) {
					var filePath = res.tempFilePath;
					uni.openDocument({
						filePath: filePath,
						fileType: 'pdf',
						showMenu: true,
						success: function(res) {
							console.log('打开文档成功');
						},
						fail: function(err) {
							console.log(err.errMsg);
							uni.showModal({
								title: '打开文档_fail',
								content: err.errMsg + fileUrl,
							})
						},
					});
				},
				fail: function(err) {
					uni.showModal({
						title: '下载文档_fail',
						content: err.errMsg + fileUrl,
					})
				},
			});
			// uni.navigateTo({
			// 	url: '/pages/houseViewing/interlinking?id=' +
			// 		encodeURIComponent(fileList),
			// });
		})
	}
	const doPayment = (paymentData) => {
		return new Promise((resolve, reject) => {
			console.log(paymentData, 8888888888)
			wx.requestPayment({
				...paymentData, // 这里传入必要的支付参数
				success(res) {
					resolve(res);
				},
				fail(err) {
					console.error('支付失败', err);
				},
				complete() {
					console.log('支付结果回调');
				}
			});
		});
	}
	const gopay = (houseId) => {
		let url = '/api/mobile/payment/generateOrder'
		post(url, {
			"userId": userId.value, //用户ID
			"orderInfo": "测试", //订单标题
			"houseId": houseId, //房屋ID
			'orgFrontUrl': 'pages/mine/succer/succer'
		}).then((res) => {
			console.log(res, 3333)
			doPayment({
				"timeStamp": res.data.timeStamp,
				"nonceStr": res.data.nonceStr,
				"package": res.data.package,
				"signType": res.data.signType,
				"paySign": res.data.paySign,
			}).then(result => {
				// 支付成功后的逻辑处理
				console.log('支付成功的结果:', result);
				let urls = '/api/mobile/payment/updateHouseRoom'
				get(urls, {
					outTrace: res.data.outTrace,
				}).then((res) => {
					console.log('十秒前88888888888', res)
				})
				setTimeout(() => {
					let url = '/api/mobile/payment/getPayResult'
					get(url, {
						outTrace: res.data.outTrace,
					}).then((res) => {
						console.log('十秒后88888888888', res)
					})
				}, 10000)
			}).catch(error => {
				// 处理支付失败的情况
				console.error('支付失败的错误:', error);
			});
		})
	}
	const payment = () => {
		uni.showModal({
			title: '提示',
			content: '等待房东签约中',
			success: function(res) {
				if (res.confirm) {
					console.log('用户点击确定');
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	const userId = ref()
	const yaoshi = (house, id, item, keytype) => {
		uni.getStorage({
			key: 'lifeData',
			success: function(res) {
				uni.showModal({
					title: '提示',
					content: '请在' + item + '钥匙托放门店取钥匙',
					success: function(restwo) {
						if (restwo.confirm) {
							substance.length = 0
							let urls = "/api/user/selectKey"
							// console.log(res.data.vuex_user.userId, 9999999)
							post(urls, {
								"userId": res.data.vuex_user.userId,
								'houseId': house,
								'state': 2,
								'id': id
							}).then((itemss) => {
								console.log(itemss.data, 88888)
								substance.push(itemss.data)
								console.log(substance, 9999)
								viewHouseRecord(one.value)
							})
						} else if (restwo.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			fail: function(res) {
				if (res.errMsg == 'getStorage:fail data not found') {
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}
			}
		})
	}
	const mima = (keyType, house, id) => {
		if (keyType != null) {
			uni.showModal({
				title: '提示',
				content: '您的钥匙密码为：' + keyType + `${'\n'}如果您已看房请点击下方确定按钮`,
				success: function(restwo) {
					if (restwo.confirm) {
						substance.length = 0
						let urls = "/api/user/selectKey"
						post(urls, {
							"userId": userId.value,
							'houseId': house,
							'state': 3,
							'id': id
						}).then((itemss) => {
							console.log(itemss.data, 88888)
							substance.push(itemss.data)
							console.log(substance, 9999)
							viewHouseRecord(one.value)
						})
					} else if (restwo.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		} else {
			uni.showModal({
				title: '提示',
				content: '还未到您的看房时间，请在看房时间内查看密码',
				success: function(restwo) {
					if (restwo.confirm) {
						console.log('用户点击确定')
					} else if (restwo.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}
	}
	// 签合同
	const show = ref(false)
	const selecteds = reactive({
		house: '',
		price: '',
		approximately: '15',
		specific: '',
		rentDate: '',
		deposit: '',
	})
	const oness = reactive({
		one: '',
		two: '',
		three: '',
	})
	const signup = (house, price, payType) => {
		let urlsone = "/api/user/toSignFDContract"
		post(urlsone, {
			'userId': userId.value,
			'houseId': house,
		}).then((resone) => {
			console.log(resone, 8888888)
			if (resone.data !== undefined) {
				if (resone.msg == '未认证') {
					uni.showModal({
						title: '提示',
						content: '您有未签署的合同，点击确定按钮认证个人信息再去签署合同吧',
						// showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/mine/authentication'
								});
							}
						}
					});
				} else {
					console.log('用户点击确定8888888888');
					uni.showModal({
						title: '提示',
						content: '您有未签署的合同，点击确定去签约吧',
						success: function(resoo) {
							if (resoo.confirm) {
								console.log('用户点击确定99999999999');
								let urlstwo = "/api/user/signContract"
								post(urlstwo, resone.data).then((itemss) => {
									console.log(itemss.data, 88888)
									let fileList = JSON.stringify(
										itemss
										.data)
									uni.navigateTo({
										url: '/pages/houseViewing/interlinking?id=' +
											encodeURIComponent(
												fileList),
									});
								})
							} else if (resoo.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
			} else {
				console.log(house, 888888)
				selecteds.house = house
				selecteds.price = price
				selecteds.specific = payType
				selecteds.approximately = 15
				oness.one = price
				oness.two = payType
				oness.three = 15
				show.value = true
				console.log(selecteds, 9999)
			}
		})
	}
	const title = ref('最终成交价');
	const start = () => {
		// let that = this
		if (test.isEmpty(selecteds.rentDate)) {
			return wx.showToast({
				title: '请输入租期（月）',
				icon: 'none',
				duration: 2000
			})
		}
		console.log('888899999', selecteds)
		let urls = "/api/user/signContract"
		console.log(selecteds, 9999999)
		show.value = false
		post(urls, {
			"userId": userId.value,
			'houseId': selecteds.house,
			'payRentOne': selecteds.price, //最终价格
			'specific': selecteds.specific, //月付，年付
			'approximately': selecteds.approximately, //多少号交租
			'rentDate': selecteds.rentDate, //租期
			'deposit': selecteds.deposit, //押金
		}).then((itemss) => {
			console.log(itemss.data, 88888)
			let fileList = JSON.stringify(itemss.data)
			uni.navigateTo({
				url: '/pages/houseViewing/interlinking?id=' +
					encodeURIComponent(fileList),
			});
		})
	}
	const cancelss = () => {
		if (selecteds.specific == '') {
			console.log(222222222222, oness.two)
			selecteds.specific = oness.two
		}
		if (selecteds.approximately == '') {
			selecteds.approximately = oness.three
		}
		show.value = false
	}
	// 以上签合同
	const comment = (house) => {
		console.log('评论')
		uni.navigateTo({
			url: `/pages/houseViewing/comment?userId=${userId.value}&house=${house}`
		});
	}
	const viewHouseRecord = (id) => {
		uni.getStorage({
			key: 'lifeData',
			success: function(res) {
				substance.length = 0
				let urls = "/api/user/viewHouseRecord"
				// console.log(res.data.vuex_user.userId, 9999999)
				post(urls, {
					"userId": res.data.vuex_user.userId,
					'state': id,
				}).then((itemss) => {
					console.log(itemss.data, 88888)
					substance.push(itemss.data)
					console.log(substance, 9999)
				})
			},
			fail: function(res) {
				if (res.errMsg == 'getStorage:fail data not found') {
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}
			}
		})
	}
	const headnavigation = ref()
	const substance = reactive([])
	const one = ref()
	// 创建响应式数据  
	const list1 = reactive([{
			name: '已预约'
		},
		{
			name: '已拿钥匙'
		},
		{
			name: '已看房'
		},
		{
			name: '已签付'
		}
	]);
	const roof = ref()
	// 定义方法  
	const click = (item) => {
		console.log('item', item);
		headnavigation.value = item.index !== undefined ? item.index : item
		console.log(headnavigation.value, 777777777777)
		one.value = parseInt(headnavigation.value) + 1
		viewHouseRecord(one.value)
	}
</script>
<style scoped lang="scss">
	.pushButton {
		display: flex;
		justify-content: flex-end;

		button {
			background-color: #FFDA00;
			font-size: 12px;
			margin-right: 10px;
			margin-left: 5px;
		}
	}

	.cycle {
		width: calc(100vw - 40px);
		margin: 0 auto;
		background-color: #ffffff;
		border-radius: 10px;
		padding: 15px 10px;

		.cycleUp {
			display: flex;
			margin: 15px 0;
			align-items: center;

			.upUp {
				color: #999999;
			}

			.upRight {
				margin-left: auto;
			}
		}
	}
</style>